package org.duang.tags;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.duang.db.common.Page;
import org.duang.kit.ToolsKit;

public class Pagination extends BodyTagSupport {

	private static final long serialVersionUID = 1L;
	
	private Page<?> page; 
	private long totalcount;
	private int pageno = 1;
	private int pagesize = 10;
	private String formid;
	private String divid;

	@Override
	public int doStartTag() throws JspException {
		try {
			if(ToolsKit.isEmpty(page)) throw new JspException("page obj is null");
			pageno = page.getPageNo();			
			totalcount = page.getTotalCount();
			pagesize =  page.getPageSize();
			formid = (ToolsKit.isEmpty(formid)) ? "" : formid;
			divid = (ToolsKit.isEmpty(divid)) ? "" : divid;
			if("".equals(formid)) throw new JspException("formid is empty");
			pageContext.getOut().write(buildHtml());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SKIP_BODY;
	}

	@Override
	public int doAfterBody() throws JspException {
		return SKIP_BODY;
	}

	@SuppressWarnings("static-access")
	@Override
	public int doEndTag() throws JspException {
		return this.EVAL_PAGE;
	}
	
	private String buildHtml(){
		if("0".equals(totalcount)) return "";
		if(page.getTotalPages() == -1) return "";
		if(0 == pagesize) return "";
		StringBuilder sb = new StringBuilder();
		sb.append("<div id='Pagination' class='pagination'>");
		sb.append("<script>");
		sb.append("_doPagination('")
			.append(pageno)
			.append("','").append(pagesize)
			.append("','").append(totalcount)
			.append("','").append(formid)
			.append("','").append(divid)
			.append("');</script></div>");
		
		return sb.toString();
	}

	public int getPagesize() {
		return pagesize;
	}

	public void setPagesize(int pagesize) {
		this.pagesize = pagesize;
	}

	public String getDivid() {
		return divid;
	}

	public void setDivid(String divid) {
		this.divid = divid;
	}
	public String getFormid() {
		return formid;
	}

	public void setFormid(String formid) {
		this.formid = formid;
	}	
	
	public Page<?> getPage() {
		return page;
	}

	public void setPage(Page<?> page) {
		this.page = page;
	}
	
}
